package cn.itguy.mobileguard.fragment;

import java.lang.reflect.Field;
import java.util.ArrayList;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.gesture.Gesture;
import android.gesture.GestureLibraries;
import android.gesture.GestureLibrary;
import android.gesture.GestureOverlayView;
import android.gesture.Prediction;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.app.Fragment;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import cn.itguy.mobileguard.ActivityJumper;
import cn.itguy.mobileguard.CommonUtils;
import cn.itguy.mobileguard.IMGPreferences;
import cn.itguy.mobileguard.R;
import cn.itguy.mobileguard.activity.MainActivity.ViewPagerVisibilityListener;
import cn.itguy.mobileguard.service.IGuardService;
import cn.itguy.mobileguard.widget.AlarmView;
import cn.itguy.mobileguard.widget.AlarmView.AlarmListener;

public class AlarmFragment extends Fragment implements AlarmListener,
		OnClickListener, ViewPagerVisibilityListener {

	private IMGPreferences preferences;

	private AlarmView alarmView;
	private CheckBox checkBox_switch;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		preferences = IMGPreferences.getInstance(getActivity());
	}

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		View rootView = inflater.inflate(R.layout.fragment_alarm, container,
				false);
		((TextView) rootView.findViewById(R.id.tv_title))
				.setText(R.string.app_name);

		alarmView = (AlarmView) rootView.findViewById(R.id.alarmView);
		alarmView.setAlarmListener(this);

		checkBox_switch = (CheckBox) rootView
				.findViewById(R.id.checkBox_switch);
		checkBox_switch.setOnClickListener(this);

		return rootView;
	}

	@Override
	public void onActivityCreated(Bundle savedInstanceState) {
		super.onActivityCreated(savedInstanceState);
	}

	@Override
	public void onVisibilityChanged(boolean visible) {
		if (visible) {
			boolean running = CommonUtils.isServiceRunning(getActivity(),
					IGuardService.class.getName());
			if (running) {
				alarmView.setProgress(alarmView.getMax());
			} else {
				alarmView.setProgress(30);
			}
			checkBox_switch.setChecked(running);
		}
	}

	@Override
	public void onAlarmStarted() {
	}

	@Override
	public void onAlarmStopped() {
	}

	@Override
	public void onClick(View v) {
		boolean checked = checkBox_switch.isChecked();
		if (checked) {
			startAlarm();
		} else {
			stopAlarm();
		}
	}

	private void startAlarm() {
		switch (preferences.getAllclearMethodIndex()) {
		case 0:
			if (TextUtils.isEmpty(preferences.getPassword())) {
				tipSetAllclearMethodDialog();
				checkBox_switch.setChecked(false);
				return;
			}
			break;
		case 1:
			if (preferences.getAllclearGestureId() == -1) {
				tipSetAllclearMethodDialog();
				checkBox_switch.setChecked(false);
				return;
			}
			break;
		case 2:
			if (TextUtils.isEmpty(preferences.getPassword())
					|| preferences.getAllclearGestureId() == -1) {
				tipSetAllclearMethodDialog();
				checkBox_switch.setChecked(false);
				return;
			}
			break;
		default:
			return;
		}

		if (preferences.getCountDialogTime() == 0) {
			alarmView.start();
			getActivity().startService(
					new Intent(getActivity(), IGuardService.class));
			return;
		}

		checkBox_switch.setChecked(false);

		final Handler countHandler = new Handler();
		final AlertDialog countDialog = new AlertDialog.Builder(getActivity())
				.setTitle(R.string.tipText_service_will_run).setMessage("")
				.setCancelable(false)
				.setNegativeButton(R.string.btnText_cancel, null).create();
		final Runnable runnable = new Runnable() {

			int time = preferences.getCountDialogTime();

			public void run() {
				if (time == 0) {
					countDialog.cancel();
					checkBox_switch.setChecked(true);
					alarmView.start();
					getActivity().startService(
							new Intent(getActivity(), IGuardService.class));
				} else {
					countDialog.setMessage(getString(R.string.formatText_count,
							time--));
					countHandler.postDelayed(this, 1000);
				}
			}
		};
		countDialog
				.setOnDismissListener(new DialogInterface.OnDismissListener() {

					public void onDismiss(DialogInterface dialog) {
						countHandler.removeCallbacks(runnable);
						dialog.cancel();
					}
				});
		countDialog.getWindow().setType(
				WindowManager.LayoutParams.TYPE_APPLICATION);
		countDialog.show();
		// countDialog.getWindow().setType(WindowManager.LayoutParams.TYPE_KEYGUARD_DIALOG);
		countHandler.post(runnable);
	}

	private void tipSetAllclearMethodDialog() {
		new AlertDialog.Builder(getActivity())
				.setTitle(R.string.tipText_tip)
				.setMessage(R.string.contentText_set_allclear_method)
				.setPositiveButton(R.string.btnText_confirm,
						new DialogInterface.OnClickListener() {

							public void onClick(DialogInterface arg0, int arg1) {
								ActivityJumper.toConfigActivity(getActivity());
							}
						}).setNegativeButton(R.string.btnText_cancel, null)
				.show();

	}

	private void stopAlarm() {
		checkBox_switch.setChecked(true);
		allclear(preferences.getAllclearMethodIndex());
	}

	private void allclear(final int allclearMethodIndex) {
		View view = LayoutInflater.from(getActivity()).inflate(
				R.layout.allclear_dialog_view, null);
		final EditText et_password = (EditText) view
				.findViewById(R.id.et_password);
		final GestureOverlayView overlay = (GestureOverlayView) view
				.findViewById(R.id.gestures_overlay);
		final GestureLibrary library = GestureLibraries.fromPrivateFile(
				getActivity(), "gestures");

		switch (allclearMethodIndex) {
		case 0:
			view.findViewById(R.id.tv_tip_input_pwd)
					.setVisibility(View.VISIBLE);
			et_password.setVisibility(View.VISIBLE);
			break;
		case 1:
			view.findViewById(R.id.tv_tip_input_gesture).setVisibility(
					View.VISIBLE);
			overlay.setVisibility(View.VISIBLE);
			view.findViewById(R.id.tv_tip).setVisibility(View.VISIBLE);
			break;
		case 2:
			view.findViewById(R.id.tv_tip_input_pwd)
					.setVisibility(View.VISIBLE);
			et_password.setVisibility(View.VISIBLE);
			view.findViewById(R.id.tv_tip_input_gesture).setVisibility(
					View.VISIBLE);
			overlay.setVisibility(View.VISIBLE);
			view.findViewById(R.id.tv_tip).setVisibility(View.VISIBLE);
			break;
		}

		new AlertDialog.Builder(getActivity())
				.setTitle(R.string.tipText_allclear)
				.setCancelable(false)
				.setView(view)
				.setPositiveButton(R.string.btnText_confirm,
						new DialogInterface.OnClickListener() {

							public void onClick(DialogInterface arg0, int arg1) {
								try {
									Field field = arg0.getClass()
											.getSuperclass()
											.getDeclaredField("mShowing");
									field.setAccessible(true);
									field.setBoolean(arg0, false);
								} catch (Exception e) {
									e.printStackTrace();
								}

								boolean allclear = false;
								switch (allclearMethodIndex) {
								case 0:
									allclear = validatePwd();
									break;
								case 1:
									allclear = validateGesture();
									break;
								case 2:
									if (validatePwd()) {
										allclear = validateGesture();
									}
									break;
								}

								if (allclear) {
									getActivity().stopService(
											new Intent(getActivity(),
													IGuardService.class));
									alarmView.stop();
									checkBox_switch.setChecked(false);

									try {
										Field field = arg0.getClass()
												.getSuperclass()
												.getDeclaredField("mShowing");
										field.setAccessible(true);
										field.setBoolean(arg0, true);
									} catch (Exception e) {
										e.printStackTrace();
									}

								}
							}

							private boolean validatePwd() {
								boolean result = false;
								if (TextUtils.equals(et_password.getText(),
										preferences.getPassword())) {
									result = true;
								} else {
									et_password
											.setError(getString(R.string.tipText_password_error));
								}
								return result;
							}

							private boolean validateGesture() {
								boolean result = false;
								Gesture gesture = overlay.getGesture();
								if (gesture != null && library != null
										&& library.load()) {
									ArrayList<Prediction> predictions = library
											.recognize(gesture);
									if (!predictions.isEmpty()
											&& predictions.get(0).score > 1.5) {
										String name = predictions.get(0).name;
										ArrayList<Gesture> gestures = library
												.getGestures(name);
										for (Gesture gest : gestures) {
											if (gest.getID() == preferences
													.getAllclearGestureId()) {
												result = true;
												break;
											}
										}
									}
								}
								if (!result) {
									Toast.makeText(
											getActivity(),
											R.string.tipText_recognize_gesture_fail,
											Toast.LENGTH_SHORT).show();
								}
								return result;
							}

						})
				.setNegativeButton(R.string.btnText_cancel,
						new DialogInterface.OnClickListener() {

							public void onClick(DialogInterface arg0, int arg1) {
								try {
									Field field = arg0.getClass()
											.getSuperclass()
											.getDeclaredField("mShowing");
									field.setAccessible(true);
									field.setBoolean(arg0, true);
								} catch (Exception e) {
									e.printStackTrace();
								}
							}
						}).show();
	}

}
